<?php
define('SE_PAGE_AJAX', TRUE);
$page = "msep_js";
include "header.php";

// THIS FILE CONTAINS RANDOM JAVASCRIPT-Y FEATURES SUCH AS POSTING COMMENTS AND DELETING ACTIONS
$task = ( isset($_POST['task']) ? $_POST['task'] : ( isset($_GET['task']) ? $_GET['task'] : NULL ) );

// RETRIEVE COMMENTS
if($task == "comment_get")
{
  // GET COMMENT TYPE, ETC
  $type = ( isset($_POST['type']) ? $_POST['type'] : NULL );
  $iden = ( isset($_POST['iden']) ? $_POST['iden'] : NULL );
  $value = ( isset($_POST['value']) ? $_POST['value'] : NULL );
  $p = ( isset($_POST['p']) ? $_POST['p'] : 1 );
  $cpp = ( isset($_POST['cpp']) ? $_POST['cpp'] : 1 );
  $object_owner = ( isset($_POST['object_owner']) ? $_POST['object_owner'] : NULL );
  $object_owner_id = ( isset($_POST['object_owner_id']) ? $_POST['object_owner_id'] : NULL );
  $tab = ( isset($_POST['tab']) ? $_POST['tab'] : NULL );
  $col = ( isset($_POST['col']) ? $_POST['col'] : NULL );

  if( !$type || !$iden || !$value ) exit();

  // CHECK TO SEE IF OWNER EXISTS
  $object_exists = FALSE;
  if( $object_owner )
  {
    $object_owner = preg_replace('/[^A-Z0-9_\.-]/i', '', $object_owner);
    $classname = "se_".$object_owner;
    if( class_exists($classname) )
    {
      $object_owner_class = new $classname($user->user_info['user_id'], $object_owner_id);
      $object_exists = $object_owner_class->{$object_owner."_exists"};
    }
  }

  if( !$owner->user_exists && !$object_exists ) exit();

  // START COMMENT OBJECT
  $comment = new se_comment($type, $iden, $value, $tab, $col);

  // GET TOTAL COMMENTS
  $total_comments = $comment->comment_total();

  // MAKE COMMENT PAGES AND GET COMMENT ARRAY
  $page_vars = make_page($total_comments, $cpp, $p);
  $comments = $comment->comment_list($page_vars[0], $cpp);

  // CONSTRUCT JSON RESPONSE
  $response_array = array(
    'total_comments'  => (int) $total_comments,
    'maxpage'         => (int) $page_vars[2],
    'p_start'         => (int) ($page_vars[0]+1),
    'p_end'           => (int) ($page_vars[0]+count($comments)),
    'p'               => (int) $page_vars[1],
    'comments'        => array()
  );

  foreach( $comments as $comment_index=>$comment_data )
  {
    // Escape trailing backslash
    if( substr($comment_data['comment_body'], -1, 1)=="\\" && substr($comment_data['comment_body'], -2, 2)!="\\\\" )
      $comment_data['comment_body'] .= "\\";

    $response_array['comments'][(int) $comment_data['comment_id']] = array
    (
      'comment_authoruser_id'           => (int)    $comment_data['comment_authoruser_id'],
      'comment_authoruser_exists'       => (bool)   $comment_data['comment_author']->user_exists,
      'comment_authoruser_private'      => (bool)   $comment_data['comment_author_private'],
      'comment_authoruser_url'          => (string) $url->url_create('profile', $comment_data['comment_author']->user_info['user_username']),
      'comment_authoruser_photo'        => (string) $comment_data['comment_author']->user_photo('./images/nophoto.gif'),
      'comment_authoruser_photo_width'  => (int)    $misc->photo_size($comment_data['comment_author']->user_photo('./images/nophoto.gif'),'75','75','w'),
      'comment_authoruser_username'     => (string) $comment_data['comment_author']->user_info['user_username'],
      'comment_authoruser_displayname'  => (string) $comment_data['comment_author']->user_displayname,
      'comment_date'                    => (string) $datetime->cdate("{$setting['setting_dateformat']} {$setting['setting_timeformat']}", $datetime->timezone($comment_data['comment_date'], $global_timezone)),
      'comment_body'                    => (string) $comment_data['comment_body']
    );
  }

  // OUTPUT JSON
  echo json_encode($response_array);
  exit();
}


// POST A COMMENT
elseif($task == "comment_post")
{
  // GET COMMENT TYPE, ETC
  $type = ( isset($_POST['type']) ? $_POST['type'] : NULL );
  $iden = ( isset($_POST['iden']) ? $_POST['iden'] : NULL );
  $value = ( isset($_POST['value']) ? $_POST['value'] : NULL );
  $tab = ( isset($_POST['tab']) ? $_POST['tab'] : NULL );
  $col = ( isset($_POST['col']) ? $_POST['col'] : NULL );
  $child = ( isset($_POST['child']) ? $_POST['child'] : FALSE );
  $tab_parent = ( isset($_POST['tab_parent']) ? $_POST['tab_parent'] : NULL );
  $col_parent = ( isset($_POST['col_parent']) ? $_POST['col_parent'] : NULL );
  $object_owner = ( isset($_POST['object_owner']) ? $_POST['object_owner'] : NULL );
  $object_owner_id = ( isset($_POST['object_owner_id']) ? $_POST['object_owner_id'] : NULL );

  if( !$type || !$iden || !$value || !$tab || !$col ) exit();

  $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type);
  $tab  = preg_replace('/[^A-Z0-9_\.-]/i', '', $tab );
  $col  = preg_replace('/[^A-Z0-9_\.-]/i', '', $col );

  // CHECK TO SEE IF OBJECT OWNER EXISTS
  if( $owner->user_exists )
  {
    $object_owner = "user";
    $object_owner_id = $owner->user_info['user_id'];
    $object_owner_class =& $owner;
  }
  elseif( $object_owner )
  {
    $object_owner = preg_replace('/[^A-Z0-9_\.-]/i', '', $object_owner);
    $classname = "se_".$object_owner;
    $object_owner_class = new $classname($user->user_info['user_id'], $object_owner_id);
    if( !$object_owner_class->{$object_owner."_exists"} ) exit();
    $owner = new se_user(Array($object_owner_class->{$object_owner."_info"}[$object_owner."_user_id"]));
  }

  else
  {
    exit();
  }

  // RETRIEVE OBJECT
  $object = $database->database_query("SELECT * FROM `se_{$tab}` WHERE `{$iden}`='{$value}'");
  if( !$database->database_num_rows($object) ) exit();
  $object_info = $database->database_fetch_assoc($object);

  // RETRIEVE OBJECT OR PARENT OF OBJECT WE ARE COMMENTING ON
  if( $child )
  {
    $permission_query = $database->database_query("SELECT `{$col_parent}_privacy` AS object_privacy, `{$col_parent}_comments` AS object_comments FROM `se_{$tab}` LEFT JOIN `se_{$tab_parent}` ON `se_{$tab}`.`{$col}_{$col_parent}_id`=`se_{$tab_parent}`.`{$col_parent}_id` WHERE `se_{$tab}`.`{$iden}`='{$value}' AND `se_{$tab_parent}`.`{$col_parent}_{$object_owner}_id`='{$object_owner_id}'");
    if( !$database->database_num_rows($permission_query) ) exit();
    $permission = $database->database_fetch_assoc($permission_query);
  }
  else
  {
    $permission = $object_info;
    $permission['object_privacy'] = $object_info[$col."_privacy"];
    $permission['object_comments'] = $object_info[$col."_comments"];
    $ownercol = ( $object_owner == $col ? $col."_id" : $col."_".$object_owner."_id" );
    if( $object_info[$ownercol] != $object_owner_id ) exit();
  }

  // CHECK IF USER IS ALLOWED TO COMMENT
  $functionname = $object_owner."_privacy_max";
  $privacy_max = $object_owner_class->$functionname($user);
  if( !($privacy_max & $permission['object_comments']) ) exit();

  // SET OBJECT TITLE
  $object_title = $object_info[$col."_title"];

  if( $tab=="eventmedia" || $tab=="groupmedia" )
  {
    $object_title = $object_owner_class->{$object_owner."_info"}[$object_owner."_title"];
  }

  if( !$object_title )
  {
    SE_Language::_preload(589);
    SE_Language::load();
    $object_title = SE_Language::_get(589);
  }

  // START COMMENT OBJECT
  $comment = new se_comment($type, $iden, $value, $tab, $col);

  // POST COMMENT
  //$comment_info = $comment->comment_post($_POST['comment_body'], $_POST['comment_secure'], $object_title, $object_owner, $object_owner_id, $permission['object_privacy']);
  $comment_info = $msep->_('comment')->comment_post($_POST['comment_body'], $_POST['comment_secure'], $object_title, $object_owner, $object_owner_id, $permission['object_privacy'], $_POST['album_id'], $_POST['album_name']);


  $is_error = $comment->is_error;
  $comment_body = ( isset($comment_info['comment_body']) ? $comment_info['comment_body'] : NULL );
  $comment_date = ( isset($comment_info['comment_date']) ? $comment_info['comment_date'] : NULL );

  // RUN JAVASCRIPT FUNCTION (JSON)
  echo json_encode(array(
    'is_error' => $is_error,
    'comment_body' => $comment_body,
    'comment_date' => $comment_date
  ));

  exit();
}



// EDIT A COMMENT
elseif($task == "comment_edit")
{
  // MUST BE LOGGED IN TO USE THIS TASK
  if( !$user->user_exists ) { exit(); }

  // GET COMMENT TYPE, ETC
  $comment_id = ( isset($_POST['comment_id']) ? $_POST['comment_id'] : NULL );
  $comment_edit = ( isset($_POST['comment_edit']) ? $_POST['comment_edit'] : NULL );
  $type = ( isset($_POST['type']) ? $_POST['type'] : NULL );
  $iden = ( isset($_POST['iden']) ? $_POST['iden'] : NULL );
  $value = ( isset($_POST['value']) ? $_POST['value'] : NULL );

  if( !$type || !$iden || !$value || !$comment_id || !$comment_edit ) exit();

  // START COMMENT OBJECT
  $comment = new se_comment($type, $iden, $value);

  // EDIT COMMENT
  $comment->comment_edit($comment_id, $comment_edit);

  // RUN JAVASCRIPT FUNCTION (JSON)
  echo json_encode(array(
    'is_error' => FALSE
  ));

  exit();
}


// DELETE A COMMENT
elseif( $task == "comment_delete" )
{
  // MUST BE LOGGED IN TO USE THIS TASK
  if( !$user->user_exists ) { exit(); }

  // GET COMMENT TYPE, ETC
  $comment_id = ( isset($_POST['comment_id']) ? $_POST['comment_id'] : NULL );
  $type = ( isset($_POST['type']) ? $_POST['type'] : NULL );
  $iden = ( isset($_POST['iden']) ? $_POST['iden'] : NULL );
  $value = ( isset($_POST['value']) ? $_POST['value'] : NULL );
  $tab = ( isset($_POST['tab']) ? $_POST['tab'] : NULL );
  $col = ( isset($_POST['col']) ? $_POST['col'] : NULL );
  $child = ( isset($_POST['child']) ? $_POST['child'] : FALSE );
  $tab_parent = ( isset($_POST['tab_parent']) ? $_POST['tab_parent'] : NULL );
  $col_parent = ( isset($_POST['col_parent']) ? $_POST['col_parent'] : NULL );
  $object_owner = ( isset($_POST['object_owner']) ? $_POST['object_owner'] : NULL );
  $object_owner_id = ( isset($_POST['object_owner_id']) ? $_POST['object_owner_id'] : NULL );

  if( !$type || !$iden || !$value || !$tab || !$col || !$comment_id ) exit();

  $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type);
  $tab  = preg_replace('/[^A-Z0-9_\.-]/i', '', $tab );
  $col  = preg_replace('/[^A-Z0-9_\.-]/i', '', $col );

  // CHECK TO SEE IF OBJECT OWNER EXISTS
  if( $owner->user_exists )
  {
    $object_owner = "user";
    $object_owner_id = $owner->user_info['user_id'];
    $object_owner_class =& $owner;
  }
  elseif( $object_owner )
  {
    $object_owner = preg_replace('/[^A-Z0-9_\.-]/i', '', $object_owner);
    $classname = "se_".$object_owner;
    $object_owner_class = new $classname($user->user_info['user_id'], $object_owner_id);
    if( !$object_owner_class->{$object_owner."_exists"} ) exit();
  }
  else
  {
    exit();
  }

  // RETRIEVE OBJECT
  $object = $database->database_query("SELECT * FROM `se_{$tab}` WHERE `{$iden}`='{$value}'");
  if( !$database->database_num_rows($object) ) exit();
  $object_info = $database->database_fetch_assoc($object);

  // RETRIEVE OBJECT OR PARENT OF OBJECT WE ARE COMMENTING ON
  if( $child )
  {
    $parent_query = $database->database_query("SELECT `{$col_parent}_{$object_owner}_id` AS object_owner_id FROM `se_{$tab}` LEFT JOIN `se_{$tab_parent}` ON `se_{$tab}`.`{$col}_{$col_parent}_id`=`se_{$tab_parent}`.`{$col_parent}_id` WHERE `se_{$tab}`.`{$iden}`='{$value}' AND `se_{$tab_parent}`.`{$col_parent}_{$object_owner}_id`='{$object_owner_id}'");
    if( !$database->database_num_rows($parent_query) ) exit();
    $parent = $database->database_fetch_assoc($parent_query);
    $object_info['object_owner_id'] = $parent['object_owner_id'];
  }
  else
  {
    $ownercol = ( $object_owner == $col ? $col."_id" : $col."_".$object_owner."_id" );
    if( $object_info[$ownercol] != $object_owner_id ) exit();
    $object_info['object_owner_id'] = $object_info[$owner_col];
  }

  // RETRIEVE COMMENT
  $comment_info = $database->database_fetch_assoc($database->database_query("SELECT `{$type}comment_authoruser_id` AS comment_authoruser_id FROM `se_{$type}comments` WHERE `{$type}comment_{$iden}`='{$value}' AND `{$type}comment_id`='{$comment_id}'"));

  // CHECK IF USER IS ALLOWED TO DELETE COMMENT
  $functionname = $object_owner."_privacy_max";
  $privacy_max = $object_owner_class->$functionname($user);
  if( !($privacy_max & $object_owner_class->{"moderation_privacy"}) && $user->user_info['user_id'] != $comment_info['comment_authoruser_id'] ) exit();

  // START COMMENT OBJECT
  $comment = new se_comment($type, $iden, $value, $tab, $col);

  // DELETE COMMENT
  $comment->comment_delete($comment_id);

  // RUN JAVASCRIPT FUNCTION (JSON)
  echo json_encode(array(
    'is_error' => FALSE
  ));

  exit();
}
elseif($task == "suggest_friend")
{
      // MUST BE LOGGED IN TO USE THIS TASK
      if( !$user->user_exists )
      {
            echo json_encode(array('results'=>array()));
            exit;
      }

      // GET USER INPUT AND LIMIT
      $input = strtolower( $_GET['input'] );
      $len = strlen_utf8($input);
      $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 20;

      // RETRIEVE FITTING FRIENDS
      $results = array();
      $sql = "SELECT user_id, user_username, user_fname, user_lname, user_photo FROM se_friends LEFT JOIN se_users ON se_friends.friend_user_id1='{$user->user_info['user_id']}' AND se_users.user_id=se_friends.friend_user_id2 WHERE se_friends.friend_status=1 AND (SUBSTRING(user_username, 1, $len)='$input' OR SUBSTRING(user_fname, 1, $len)='$input' OR SUBSTRING(user_lname, 1, $len)='$input') LIMIT $limit";
      $resource = $database->database_query($sql);

      while( $friend_info = $database->database_fetch_assoc($resource) )
      {
            $friend = new se_user();
            $friend->user_info['user_id'] = $friend_info['user_id'];
            $friend->user_info['user_username'] = $friend_info['user_username'];
            $friend->user_info['user_fname'] = $friend_info['user_fname'];
            $friend->user_info['user_lname'] = $friend_info['user_lname'];
            $friend->user_info['user_photo'] = $friend_info['user_photo'];
            $friend->user_displayname();

            if( !$setting['setting_username'] ) { $friend_info['user_username'] = $friend->user_displayname; }

            $results[] = array(
                  "id"          => $friend_info['user_id'],
                  "value"       => $friend->user_displayname,
                  "info"        => $friend->user_displayname,
                  "photo"       => $friend->user_photo("./images/nophoto.gif"),
                  "photo_width" => $misc->photo_size($friend->user_photo("./images/nophoto.gif"),'50','50','w')
            );
      }

      // OUTPUT JSON
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
      header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
      header("Pragma: no-cache"); // HTTP/1.0
      header("Content-Type: application/json");
      echo json_encode(array('results' => &$results));
      exit;
}
// CHECK IF USER'S FRIEND EXISTS
elseif( $task == "check_friend" )
{
      // MUST BE LOGGED IN TO USE THIS TASK
      if( !$user->user_exists )
      {
        echo json_encode(array('result'=>array()));
        exit();
      }

      // GET USER INPUT AND LIMIT
      $input = strtolower( $_GET['input'] );

      $sql = "SELECT NULL FROM se_friends LEFT JOIN se_users ON se_friends.friend_user_id1='{$user->user_info['user_id']}' AND se_users.user_id=se_friends.friend_user_id2 WHERE se_users.user_id='{$input}' AND se_friends.friend_status=1 LIMIT 1";
      $resource = $database->database_query($sql);
      $user_exists = ( $resource && $database->database_num_rows($resource) );

      // OUTPUT JSON
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
      header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
      header("Pragma: no-cache"); // HTTP/1.0
      header("Content-Type: application/json");
      echo json_encode(array('user_exists' => (bool)$user_exists));
      exit();
}
elseif($task == "total_comments")
{
  $msep->setPlugin($_POST['plugin'], false);
  echo json_encode(array('total_comments' => $msep->_('misc')->total_comments($_POST['object_id'])));
  exit;
}
?>